<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>我来学Kotlin-基础之基础类型 - (power up)</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="Kevin Jiang" /><meta name="description" content="在Kotlin，一切皆对象，我们可以在任何变量上调用成员函数和属性。有些类型是内置的，因为它们的实现是经过优化的，但是对于用户来说，它们看起" /><meta name="keywords" content="KevinJiang, AI大模型, AI落地, 全栈工程师, Java, Spring Boot" />






<meta name="generator" content="Hugo 0.84.4 with theme even" />


<link rel="canonical" href="http://kevinjiang.info/post/kotlin/%E6%88%91%E6%9D%A5%E5%AD%A6kotlin-%E5%9F%BA%E7%A1%80%E4%B9%8B%E5%9F%BA%E7%A1%80%E7%B1%BB%E5%9E%8B/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.78f8f17bab244b9ee62ad16480c9584d5fc2db06ae20681d1ca225cefd80767c.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="我来学Kotlin-基础之基础类型" />
<meta property="og:description" content="在Kotlin，一切皆对象，我们可以在任何变量上调用成员函数和属性。有些类型是内置的，因为它们的实现是经过优化的，但是对于用户来说，它们看起" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://kevinjiang.info/post/kotlin/%E6%88%91%E6%9D%A5%E5%AD%A6kotlin-%E5%9F%BA%E7%A1%80%E4%B9%8B%E5%9F%BA%E7%A1%80%E7%B1%BB%E5%9E%8B/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2017-06-14T11:45:13+00:00" />
<meta property="article:modified_time" content="2017-06-14T11:45:13+00:00" />

<meta itemprop="name" content="我来学Kotlin-基础之基础类型">
<meta itemprop="description" content="在Kotlin，一切皆对象，我们可以在任何变量上调用成员函数和属性。有些类型是内置的，因为它们的实现是经过优化的，但是对于用户来说，它们看起"><meta itemprop="datePublished" content="2017-06-14T11:45:13+00:00" />
<meta itemprop="dateModified" content="2017-06-14T11:45:13+00:00" />
<meta itemprop="wordCount" content="2601">
<meta itemprop="keywords" content="Kotlin,Kotlin教程," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="我来学Kotlin-基础之基础类型"/>
<meta name="twitter:description" content="在Kotlin，一切皆对象，我们可以在任何变量上调用成员函数和属性。有些类型是内置的，因为它们的实现是经过优化的，但是对于用户来说，它们看起"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">(Power up)</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">归档</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">标签</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">分类</li>
      </a><a href="/resume/">
        <li class="mobile-menu-item">简历</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">(Power up)</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">归档</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/resume/">简历</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">我来学Kotlin-基础之基础类型</h1>

      <div class="post-meta">
        <span class="post-time"> 2017-06-14 </span>
        <div class="post-category">
            <a href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/"> 编程语言 </a>
            </div>
          <span class="more-meta"> 约 2601 字 </span>
          <span class="more-meta"> 预计阅读 6 分钟 </span>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#字面量">字面量</a></li>
    <li><a href="#使用下划线11或更高版本">使用下划线（1.1或更高版本）</a></li>
    <li><a href="#representation">Representation</a></li>
    <li><a href="#显示转换">显示转换</a></li>
    <li><a href="#运算符">运算符</a></li>
  </ul>

  <ul>
    <li><a href="#字符串字面量">字符串字面量</a></li>
    <li><a href="#字符串模板">字符串模板</a></li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>在Kotlin，一切皆对象，我们可以在任何变量上调用成员函数和属性。有些类型是内置的，因为它们的实现是经过优化的，但是对于用户来说，它们看起来就像普通的类。本节描述这些类型中的大多数： numbers, characters, booleans and arrays.</p>
<!-- raw HTML omitted -->
<h1 id="数字类型">数字类型</h1>
<p>Kotlin以一种接近Java的方式处理数字，但不完全一样。例如，对于数字没有隐式转换，而在某些情况下，字面量略有不同。Kotlin提供如下内置的数字类型（与Java接近）：</p>
<table>
<thead>
<tr>
<th>Type</th>
<th>Bit width</th>
</tr>
</thead>
<tbody>
<tr>
<td>Double</td>
<td>64</td>
</tr>
<tr>
<td>Float</td>
<td>32</td>
</tr>
<tr>
<td>Long</td>
<td>64</td>
</tr>
<tr>
<td>Int</td>
<td>32</td>
</tr>
<tr>
<td>Short</td>
<td>16</td>
</tr>
<tr>
<td>Byte</td>
<td>8</td>
</tr>
</tbody>
</table>
<p><strong>注意：在Kotlin中字符不是数字</strong></p>
<h2 id="字面量">字面量</h2>
<p>整数字面量如下：</p>
<ul>
<li>十进制：123
<ul>
<li>Long长整形使用L标识：123L</li>
</ul>
</li>
<li>十六进制：0x0F</li>
<li>二进制：0b00001011</li>
</ul>
<p><strong>注意：不支持八进制字面量</strong></p>
<p>Kotlin支持常见的浮点数字：</p>
<ul>
<li>Double双精度是默认的浮点数字：123.5, 123.5e10</li>
<li>单精度使用f或者F标识：123.5f</li>
</ul>
<h2 id="使用下划线11或更高版本">使用下划线（1.1或更高版本）</h2>
<p>比较长的数字使用下划线可以更易于阅读，这和Swift的使用方法一样</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">oneMillion</span> <span class="p">=</span> <span class="m">1</span><span class="n">_000_000</span>
<span class="k">val</span> <span class="py">creditCardNumber</span> <span class="p">=</span> <span class="m">1234</span><span class="n">_5678_9012_3456L</span>
<span class="k">val</span> <span class="py">socialSecurityNumber</span> <span class="p">=</span> <span class="m">999</span><span class="n">_99_9999L</span>
<span class="k">val</span> <span class="py">hexBytes</span> <span class="p">=</span> <span class="m">0xFF</span><span class="n">_EC_DE_5E</span>
<span class="k">val</span> <span class="py">bytes</span> <span class="p">=</span> <span class="m">0</span><span class="n">b11010010_01101001_10010100_10010010</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="representation">Representation</h2>
<p>在JVM平台，数字被物理地存储为JVM原始类型，除非我们需要一个可空的数字引用（例如Int?）或者泛型。在后一种情况下数字会被装箱（boxed）。</p>
<p><strong>注意：装箱后的数字不一定会保持引用</strong></p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">a</span><span class="p">:</span> <span class="n">Int</span> <span class="p">=</span> <span class="m">10000</span>
<span class="n">print</span><span class="p">(</span><span class="n">a</span> <span class="o">===</span> <span class="n">a</span><span class="p">)</span> <span class="c1">// Prints &#39;true&#39;
</span><span class="c1"></span><span class="k">val</span> <span class="py">boxedA</span><span class="p">:</span> <span class="n">Int</span><span class="p">?</span> <span class="p">=</span> <span class="n">a</span>
<span class="k">val</span> <span class="py">anotherBoxedA</span><span class="p">:</span> <span class="n">Int</span><span class="p">?</span> <span class="p">=</span> <span class="n">a</span>
<span class="n">print</span><span class="p">(</span><span class="n">boxedA</span> <span class="o">===</span> <span class="n">anotherBoxedA</span><span class="p">)</span> <span class="c1">// !!!Prints &#39;false&#39;!!!
</span></code></pre></td></tr></table>
</div>
</div><p>但是会保持值的相等（使用两个等号<code>==</code>）。三个等号（<code>===</code>）会判断是否是同一个对象，就是上面说的引用，内存地址相等。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">a</span><span class="p">:</span> <span class="n">Int</span> <span class="p">=</span> <span class="m">10000</span>
<span class="n">print</span><span class="p">(</span><span class="n">a</span> <span class="o">==</span> <span class="n">a</span><span class="p">)</span> <span class="c1">// Prints &#39;true&#39;
</span><span class="c1"></span><span class="k">val</span> <span class="py">boxedA</span><span class="p">:</span> <span class="n">Int</span><span class="p">?</span> <span class="p">=</span> <span class="n">a</span>
<span class="k">val</span> <span class="py">anotherBoxedA</span><span class="p">:</span> <span class="n">Int</span><span class="p">?</span> <span class="p">=</span> <span class="n">a</span>
<span class="n">print</span><span class="p">(</span><span class="n">boxedA</span> <span class="o">==</span> <span class="n">anotherBoxedA</span><span class="p">)</span> <span class="c1">// Prints &#39;true&#39;
</span></code></pre></td></tr></table>
</div>
</div><h2 id="显示转换">显示转换</h2>
<p>由于表示方法的不同，较小的类型不是较大类型的子类型。如果是，我们将会遇到以下问题：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="c1">// 假设有如下代码，实际是不能编译的：
</span><span class="c1"></span><span class="k">val</span> <span class="py">a</span><span class="p">:</span> <span class="n">Int</span><span class="p">?</span> <span class="p">=</span> <span class="m">1</span> <span class="c1">// 一个Int对象（在Java是java.lang.Integer）
</span><span class="c1"></span><span class="k">val</span> <span class="py">b</span><span class="p">:</span> <span class="n">Long</span><span class="p">?</span> <span class="p">=</span> <span class="n">a</span> <span class="c1">// 隐式转换为Long对象（在Java是java.lang.Long）
</span><span class="c1"></span><span class="n">print</span><span class="p">(</span><span class="n">a</span> <span class="o">==</span> <span class="n">b</span><span class="p">)</span> <span class="c1">// 惊讶！这会打印出`false`，两个等号使用的是equals方法来判断相等性，a和b的类型不一样，所以打开出来是false
</span></code></pre></td></tr></table>
</div>
</div><p>所以不仅在引用上，而且相等性在这里也默默的消失了。因此较小类型不隐式的转换成较大类型。这意味着，在没有显示转换时，我们不能将一个<code>Byte</code>类型赋值给一个<code>Int</code>类型：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">b</span><span class="p">:</span> <span class="n">Byte</span> <span class="p">=</span> <span class="m">1</span> <span class="c1">// OK, literals are checked statically
</span><span class="c1"></span><span class="k">val</span> <span class="py">i</span><span class="p">:</span> <span class="n">Int</span> <span class="p">=</span> <span class="n">b</span> <span class="c1">// ERROR
</span></code></pre></td></tr></table>
</div>
</div><p>使用显示转换到更宽（较大）的数字：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">i</span><span class="p">:</span> <span class="n">Int</span> <span class="p">=</span> <span class="n">b</span><span class="p">.</span><span class="n">toInt</span><span class="p">()</span> <span class="c1">// OK: explicitly widened
</span></code></pre></td></tr></table>
</div>
</div><p>每一个数字类型支持下面的转换：</p>
<ul>
<li>toByte(): Byte</li>
<li>toShort(): Short</li>
<li>toInt(): Int</li>
<li>toLong(): Long</li>
<li>toFloat(): Float</li>
<li>toDouble(): Double</li>
<li>toChar(): Char</li>
</ul>
<p>隐式转换的缺失很少会被注意到，因为类型是从上下文推断出来的，算术运算符做了重载，例如：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">l</span> <span class="p">=</span> <span class="m">1L</span> <span class="p">+</span> <span class="m">3</span> <span class="c1">// Long + Int =&gt; Long
</span></code></pre></td></tr></table>
</div>
</div><h2 id="运算符">运算符</h2>
<p>Kotlin支持标准的数学运算集，它们是以类成员的方式定义的（但是编译器会将调用优化为相应的指令）。</p>
<p>对于位运算，不是使用特殊字符（像&raquo;, &laquo;），而是以命名函数的方式进行中缀调用，例如：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">x</span> <span class="p">=</span> <span class="p">(</span><span class="m">1</span> <span class="n">shl</span> <span class="m">2</span><span class="p">)</span> <span class="n">and</span> <span class="m">0x000FF000</span>
</code></pre></td></tr></table>
</div>
</div><p>这里是完整的位运算列表（只针对<code>Int</code>和<code>Long</code>类型）：</p>
<ul>
<li><code>shl(bits)</code> – 左移 (Java&rsquo;s &laquo;)</li>
<li><code>shr(bits)</code> – 右移 (Java&rsquo;s &raquo;)</li>
<li><code>ushr(bits)</code> – 不带符号的右移 (Java&rsquo;s &raquo;&gt;)</li>
<li><code>and(bits)</code> – 与</li>
<li><code>or(bits)</code> – 或</li>
<li><code>xor(bits)</code> – 异或</li>
<li><code>inv()</code> – 按位反转：00000001 -&gt; 11111110</li>
</ul>
<h1 id="字符类型">字符类型</h1>
<p>字符使用<code>Char</code>表示，不能直接当作数字来对待（相对于Java字符与ascii整数是可以互换的）：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">fun</span> <span class="nf">check</span><span class="p">(</span><span class="n">c</span><span class="p">:</span> <span class="n">Char</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">c</span> <span class="o">==</span> <span class="m">1</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// ERROR: incompatible types
</span><span class="c1"></span>        <span class="c1">// ...
</span><span class="c1"></span>    <span class="p">}</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>字符字面量使用单引号：<code>'1'</code>。特殊字条使用反斜杠进行转义，支持：<code>\t</code>, <code>\b</code>, <code>\n</code>, <code>\r</code>, <code>\'</code>, <code>\&quot;</code>, <code>\\</code>, <code>\$</code>。其他的字符可以使用Unicode转义语法：<code>\uFF00</code>。我们可以显示的把字符转换成数字，例如把<code>'1'</code>转换成<code>1</code>：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">fun</span> <span class="nf">decimalDigitValue</span><span class="p">(</span><span class="n">c</span><span class="p">:</span> <span class="n">Char</span><span class="p">):</span> <span class="n">Int</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">c</span> <span class="o">!in</span> <span class="sc">&#39;0&#39;</span><span class="o">..</span><span class="sc">&#39;9&#39;</span><span class="p">)</span>
        <span class="k">throw</span> <span class="n">IllegalArgumentException</span><span class="p">(</span><span class="s2">&#34;Out of range&#34;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">c</span><span class="p">.</span><span class="n">toInt</span><span class="p">()</span> <span class="p">-</span> <span class="sc">&#39;0&#39;</span><span class="p">.</span><span class="n">toInt</span><span class="p">()</span> <span class="c1">// Explicit conversions to numbers
</span><span class="c1"></span><span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>跟数字一样，在需要可空类型的时候会进行装箱，并且不会保持引用的不变。</p>
<h1 id="布尔类型">布尔类型</h1>
<p>布尔类型使用<code>Boolean</code>来表示，只有两个值：<code>true</code>和<code>false</code>。同样在需要可空类型的时候会进行装箱。内置的运算符如下：</p>
<ul>
<li><code>||</code> - 或</li>
<li><code>&amp;&amp;</code> - 与</li>
<li><code>!</code> - 非</li>
</ul>
<h1 id="数组">数组</h1>
<p>数组在Kotlin以<code>Array</code>类表示，它具有get和set方法（可以使用[]重载调用），以及size属性，还有一些其他有用的方法：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">class</span> <span class="nc">Array</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="k">private</span> <span class="k">constructor</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">val</span> <span class="py">size</span><span class="p">:</span> <span class="n">Int</span>
    <span class="k">operator</span> <span class="k">fun</span> <span class="nf">get</span><span class="p">(</span><span class="n">index</span><span class="p">:</span> <span class="n">Int</span><span class="p">):</span> <span class="n">T</span>
    <span class="k">operator</span> <span class="k">fun</span> <span class="nf">set</span><span class="p">(</span><span class="n">index</span><span class="p">:</span> <span class="n">Int</span><span class="p">,</span> <span class="n">value</span><span class="p">:</span> <span class="n">T</span><span class="p">):</span> <span class="n">Unit</span>

    <span class="k">operator</span> <span class="k">fun</span> <span class="nf">iterator</span><span class="p">():</span> <span class="n">Iterator</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span>
    <span class="c1">// ...
</span><span class="c1"></span><span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><p>要创建一个数组，我们可以使用库函数<code>arrayOf()</code>和传递一些值给函数，<code>arrayOf(1, 2, 3)</code>会创建一个数组[1, 2, 3]。<code>arrayOfNulls(size: Int)</code>库函数用来创建给定大小的数组，所有元素的值都为null。另一个选择是使用工厂方法，传一个大小值和一个给定索引值返回元素值的函数：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="c1">// Creates an Array&lt;String&gt; with values [&#34;0&#34;, &#34;1&#34;, &#34;4&#34;, &#34;9&#34;, &#34;16&#34;]
</span><span class="c1"></span><span class="k">val</span> <span class="py">asc</span> <span class="p">=</span> <span class="n">Array</span><span class="p">(</span><span class="m">5</span><span class="p">,</span> <span class="p">{</span> <span class="n">i</span> <span class="o">-&gt;</span> <span class="p">(</span><span class="n">i</span> <span class="p">*</span> <span class="n">i</span><span class="p">).</span><span class="n">toString</span><span class="p">()</span> <span class="p">})</span>
</code></pre></td></tr></table>
</div>
</div><p>上面说过，<code>[]</code>操作符全调用<code>get()</code>和<code>set()</code>方法。</p>
<p><strong>注意：不像Java，Kotlin的数组类型是不能转变的。这意味着不能把<code>Array&lt;String&gt;</code>赋值为<code>Array&lt;Any&gt;</code>，以防止可能的运行时错误（但是仍然可以使用<code>Array&lt;out Any&gt;</code>），这是Kotlin添加的协变和逆变概念</strong></p>
<p>Kotlin还有其他的类来表示其他的的基础类型数组而不需要装箱：<code>ByteArray</code>, <code>ShortArray</code>, <code>IntArray</code>等等。这些类并不是继承自<code>Array</code>，但是他们有着相关的方法和属性。每一个都有相应的库函数：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">x</span><span class="p">:</span> <span class="n">IntArray</span> <span class="p">=</span> <span class="n">intArrayOf</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">,</span> <span class="m">3</span><span class="p">)</span>
<span class="n">x</span><span class="p">[</span><span class="m">0</span><span class="p">]</span> <span class="p">=</span> <span class="n">x</span><span class="p">[</span><span class="m">1</span><span class="p">]</span> <span class="p">+</span> <span class="n">x</span><span class="p">[</span><span class="m">2</span><span class="p">]</span>
</code></pre></td></tr></table>
</div>
</div><h1 id="字符串">字符串</h1>
<p>字符串使用<code>String</code>类表示，并且是不可变的（immutable）。字符串是以字符组成，每一个元素是一个字条，可以使用索引来访问每个位置上的字符值：<code>s[i]</code>，可以使用for循环来迭代：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">for</span> <span class="p">(</span><span class="n">c</span> <span class="k">in</span> <span class="n">str</span><span class="p">)</span> <span class="p">{</span>
    <span class="n">println</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="字符串字面量">字符串字面量</h2>
<p>Kotlin有两种字面量：双引号和三个双引号包裹。前一种可以包含转义字符，后一种可以显示的换行。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">s</span> <span class="p">=</span> <span class="s2">&#34;Hello, world!</span><span class="se">\n</span><span class="s2">&#34;</span>
<span class="k">val</span> <span class="py">text</span> <span class="p">=</span> <span class="s">&#34;&#34;&#34;
</span><span class="s">    for (c in &#34;foo&#34;)
</span><span class="s">        print(c)
</span><span class="s">&#34;&#34;&#34;</span>
</code></pre></td></tr></table>
</div>
</div><p>可以使用<code>trimMargin()</code>方法删除原始字符串前面的空白，默认使用竖线<code>|</code>，但是可以其他的字符达到同样的效果，例如<code>trimMargin(&quot;&gt;&quot;)</code>：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">text</span> <span class="p">=</span> <span class="s">&#34;&#34;&#34;
</span><span class="s">    |Tell me and I forget.
</span><span class="s">    |Teach me and I remember.
</span><span class="s">    |Involve me and I learn.
</span><span class="s">    |(Benjamin Franklin)
</span><span class="s">    &#34;&#34;&#34;</span><span class="p">.</span><span class="n">trimMargin</span><span class="p">()</span>
</code></pre></td></tr></table>
</div>
</div><h2 id="字符串模板">字符串模板</h2>
<p>字符串可以包含模板表达式，例如可以把一小代码写在字符串里面，并且把代码的结果与字符串其他部分进行组装。字符串模板以<code>$</code>开头和一个简单的名字组成：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">i</span> <span class="p">=</span> <span class="m">10</span>
<span class="k">val</span> <span class="py">s</span> <span class="p">=</span> <span class="s2">&#34;i = </span><span class="si">$i</span><span class="s2">&#34;</span> <span class="c1">// 结果为：&#34;i = 10&#34;
</span></code></pre></td></tr></table>
</div>
</div><p>或者以任意被花括号包裹的表达式：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">s</span> <span class="p">=</span> <span class="s2">&#34;abc&#34;</span>
<span class="k">val</span> <span class="py">str</span> <span class="p">=</span> <span class="s2">&#34;</span><span class="si">$s</span><span class="s2">.length is </span><span class="si">${s.length}</span><span class="s2">&#34;</span> <span class="c1">// 结果为：&#34;abc.length is 3&#34;
</span></code></pre></td></tr></table>
</div>
</div><p>两种字符串方式都支持字符串模板，如果想使用<code>$</code>本身怎么办呢，可以使用<code>${'$'}</code>：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-Kotlin" data-lang="Kotlin"><span class="k">val</span> <span class="py">price</span> <span class="p">=</span> <span class="s">&#34;&#34;&#34;
</span><span class="s"></span><span class="si">${&#39;$&#39;}</span><span class="s">9.99
</span><span class="s">&#34;&#34;&#34;</span>
<span class="k">val</span> <span class="py">tpl</span> <span class="p">=</span> <span class="s2">&#34;</span><span class="si">${&#39;$&#39;}</span><span class="s2">a&#34;</span>
</code></pre></td></tr></table>
</div>
</div>
    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">Kevin Jiang</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2017-06-14
        
    </span>
  </p>
  
  <p class="copyright-item">
    <span class="item-title">许可协议</span>
    <span class="item-content"><a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank">CC BY-NC-ND 4.0</a></span>
  </p>
</div>
<div class="post-reward">
  <input type="checkbox" name="reward" id="reward" hidden />
  <label class="reward-button" for="reward">赞赏支持</label>
  <div class="qr-code">
    
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/wechat_pay_1242x1242.jpg">
        <span>微信打赏</span>
      </label>
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/alipay_600x600.jpg">
        <span>支付宝打赏</span>
      </label>
  </div>
</div><footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/kotlin/">Kotlin</a>
          <a href="/tags/kotlin%E6%95%99%E7%A8%8B/">Kotlin教程</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/kotlin/%E6%88%91%E6%9D%A5%E5%AD%A6kotlin-%E5%9F%BA%E7%A1%80%E4%B9%8B%E5%8C%85/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">我来学Kotlin-基础之包</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/kotlin/%E6%88%91%E6%9D%A5%E5%AD%A6kotlin-%E8%B5%B7%E6%AD%A5%E4%B9%8B%E4%BB%A3%E7%A0%81%E8%A7%84%E8%8C%83/">
            <span class="next-text nav-default">我来学Kotlin-起步之代码规范</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:wenlin1988@126.com" class="iconfont icon-email" title="email"></a>
      <a href="https://www.linkedin.com/in/%E6%96%87%E6%9E%97-%E8%92%8B-0a3204126/" class="iconfont icon-linkedin" title="linkedin"></a>
      <a href="https://github.com/kevindragon" class="iconfont icon-github" title="github"></a>
  <a href="http://kevinjiang.info/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 -
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    &copy;
    2015 -
    2023<span class="heart"><i class="iconfont icon-heart"></i></span><span>Kevin Jiang</span>
    <a href="https://beian.miit.gov.cn/" target="_blank">湘ICP备2022022745号</a>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c99b103c33d1539acf3025e1913697534542c4a5aa5af0ccc20475ed2863603b.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        tags: 'ams',
        }
    };
  </script>
  <script type="text/javascript" async src="/lib/mathjax/es5/tex-mml-chtml.js"></script>

<script id="baidu_analytics">
  var _hmt = _hmt || [];
  (function() {
    if (window.location.hostname === 'localhost') return;
    var hm = document.createElement("script"); hm.async = true;
    hm.src = "https://hm.baidu.com/hm.js?b73ff6d4afc4af9e582d8a5dc068bab9";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>






</body>
</html>
